package com.newlink.building.userinfo.utils

import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import okhttp3.*
import okhttp3.Request.Builder

/**
 * @Author: Jake
 * @Date: 2023/1/5
 * @Description:
 */
class Module_UserInfo_DownloadUtils private constructor() {

    private val okHttpClient: OkHttpClient = OkHttpClient()

    /**
     * @param url          下载连接
     * @param destFileDir  下载的文件储存目录
     * @param destFileName 下载文件名称
     * @param listener     下载监听
     */
    fun download(
        url: String,
        destFileDir: String,
        destFileName: String,

        listener: OnDownloadListener
    ) {
        val f1 = File(destFileDir, destFileName)
        if (f1.exists()) {
            f1.delete()
        }
        val request: Request = Builder().url(url).build()
        okHttpClient.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                // 下载失败监听回调
                listener.onDownloadFailed(e)
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                var `is`: InputStream? = null
                val buf = ByteArray(2048)
                var len = 0
                var fos: FileOutputStream? = null
                // 储存下载文件的目录
                val dir = File(destFileDir)
                if (!dir.exists()) {
                    dir.mkdirs()
                }
                val file = File(dir, destFileName)
                try {
//                    val requestBody = response.body!!
                    var requestBody = response.body!!

                    `is` = requestBody.byteStream()
                    val total = requestBody.contentLength()
                    fos = FileOutputStream(file)
                    var sum: Long = 0
                    while (`is`.read(buf).also {
                            len = it
                        } != -1) {
                        fos.write(buf, 0, len)
                        sum += len.toLong()
                        val progress = (sum * 1.0f / total * 100).toInt()
                        // 下载中更新进度条
                        listener.onDownloading(progress)
                    }
                    fos.flush()
                    // 下载完成
                    listener.onDownloadSuccess(file)
                } catch (e: Exception) {
                    listener.onDownloadFailed(e)
                } finally {
                    try {
                        `is`?.close()
                    } catch (e: IOException) {
                    }
                    try {
                        fos?.close()
                    } catch (e: IOException) {
                    }
                }
            }
        })
    }

    interface OnDownloadListener {

        fun onDownloadSuccess(file: File?)

        fun onDownloading(progress: Int)

        fun onDownloadFailed(e: Exception?)
    }

    companion object {
        private var downloadUtil: Module_UserInfo_DownloadUtils? = null
        fun get(): Module_UserInfo_DownloadUtils? {
            if (downloadUtil == null) {
                downloadUtil = Module_UserInfo_DownloadUtils()
            }
            return downloadUtil
        }
    }
}
